import { Context } from 'koa'
import { getListSer, addSer, putSer, getDetailSer, delSer } from '@/business/service'
import { userType} from '@/types'
import {  IshebeifenzuQueryType, IshebeifenzuQuerySerType, Ishebeifenzu, IshebeifenzuSer } from '@/types/equipment/shebeifenzu'
import errors from '@/app/err.type'
import { formatHumpLineTransfer } from '@/business/utils'
import { excelJsExport } from '@/business/utils/excel'
import {  excelBaseStyle } from '@/business/public/excelMap'
import ShebeifenzuTable from '@/mysql/model/equipment/shebeifenzu.model'
import { Op } from 'sequelize'

const { uploadParamsErr, getListErr, sqlErr, delErr, exportExcelErr} = errors

// 获取列表
export const getListMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { pageNum, pageSize, ...params } = ctx.query as unknown as IshebeifenzuQueryType
    const newParams = { pageNum, pageSize } as IshebeifenzuQuerySerType
    if(params.name) newParams.name = { [Op.eq]: params.name  }
    if(params.deptId) newParams.dept_id = { [Op.eq]: params.deptId  }
    
    const res = await getListSer<IshebeifenzuQuerySerType>(ShebeifenzuTable, newParams)

    ctx.state.formatData = res
    await next()
  } catch (error) {
    console.error('查询列表失败', error)
    return ctx.app.emit('error', getListErr, ctx)
  }
}
export const shebeifenzuqueryConditionsDataFn = async (params:any) => {
  try {  
    const {groupName} = params
    const whereOpt = {name:groupName};
    const res = await ShebeifenzuTable.findAll({
      raw: true, // 设置为 true，即可返回源数据
      where:whereOpt,
    });
    return res || [];    
  } catch (error) {
    console.log(error)
  }
}

// 新增
export const getAddMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { userName } = ctx.state.user as userType
    const addContent = ctx.request.body as Ishebeifenzu
    const addContent2 = { ...addContent, createBy: userName }
    const newAddContent = formatHumpLineTransfer(addContent2, 'line') as  IshebeifenzuSer

    await addSer<IshebeifenzuSer>(ShebeifenzuTable, newAddContent)
    await next()
  } catch (error) {
    console.error('新增失败', error)
    return ctx.app.emit('error', uploadParamsErr, ctx)
  }
}

// 删除
export const delMid = async (ctx: Context, next: () => Promise<void>) => {
  try {

    await delSer(ShebeifenzuTable, { table_id: ctx.state.ids })
  } catch (error) {
    console.error('删除失败', error)
    return ctx.app.emit('error', delErr, ctx)
  }

  await next()
}

// 获取详细数据
export const getDetailMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const res = await getDetailSer<IshebeifenzuSer>(ShebeifenzuTable, { table_id: ctx.state.ids  })

    ctx.state.formatData = res
  } catch (error) {
    console.error('详细数据查询错误', error)
    return ctx.app.emit('error', sqlErr, ctx)
  }

  await next()
}

// 修改
export const putMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { userName } = ctx.state.user as userType
    const res = ctx.request.body as Ishebeifenzu
    const lineData =  formatHumpLineTransfer(res, 'line') as IshebeifenzuSer
    const { table_id} = lineData

    await putSer<IshebeifenzuSer>(ShebeifenzuTable, { table_id}, { ...lineData, update_by: userName })

    await next()
  } catch (error) {
    console.error('修改失败', error)
    return ctx.app.emit('error', uploadParamsErr, ctx)
  }
}

// 导出
export const exportMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const list = ctx.state.formatData
    const {dicts} = ctx.state

    // 表格数据
    const buffer = await excelJsExport({
      sheetName: '设备分组',
      style: excelBaseStyle,
      headerColumns: [{"title":"分组名称","dataIndex":"name"},{"title":"部门","dataIndex":"dept_id"}],
      tableData: list,
      dicts
    })
    ctx.state.buffer = buffer
    await next()
  } catch (error) {
    console.error('导出失败', error)
    return ctx.app.emit('error', exportExcelErr, ctx)
  }
}